package io.renren.modules.repair.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.entity.CarTypeEntity;
import io.renren.common.utils.*;
import io.renren.modules.car.dao.CarDao;
import io.renren.modules.car.dao.CarTypeRelationDao;
import io.renren.modules.car.entity.CarEntity;
import io.renren.modules.repair.dao.ManifestDao;
import io.renren.modules.repair.entity.ManifestVO;
import io.renren.modules.repair.entity.RepairVo;
import io.renren.modules.repair.entity.req.RepairDeleteReq;
import io.renren.modules.repair.entity.req.UserRepairListReq;
import io.renren.modules.repair.mapper.RepairMapper;
import io.renren.modules.shop.service.ShopService;
import io.renren.modules.user.dao.TbUserDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import io.renren.modules.repair.dao.RepairDao;
import io.renren.modules.repair.entity.RepairEntity;
import io.renren.modules.repair.service.RepairService;


@Service("recordService")
public class RepairServiceImpl extends ServiceImpl<RepairMapper, RepairEntity> implements RepairService {
    
    private final RepairDao repairDao;
    private final CarDao carDao;
    private final ShopService shopService;
    private final TbUserDao tbUserDao;
    private final ManifestDao manifestDao;
    private final CarTypeRelationDao carTypeRelationDao;
    
    @Autowired
    public RepairServiceImpl(RepairDao repairDao, CarDao carDao, TbUserDao tbUserDao,
                             ManifestDao manifestDao, CarTypeRelationDao carTypeRelationDao,
                             ShopService shopService) {
        this.repairDao = repairDao;
        this.carDao = carDao;
        this.tbUserDao = tbUserDao;
        this.manifestDao = manifestDao;
        this.carTypeRelationDao = carTypeRelationDao;
        this.shopService = shopService;
    }
    
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<RepairEntity> page = this.page(
                new Query<RepairEntity>().getPage(params),
                new QueryWrapper<RepairEntity>()
        );

        return new PageUtils(page);
    }
    
    @Override
    public PageUtils queryUserRepairList(UserRepairListReq req) {
        PageUtils page = new PageUtils(repairDao.selectRepairList(req));
        List<?> repairLists = page.getList();
        List<RepairVo> datas = new ArrayList<>(page.getPageSize());
        repairLists.forEach(repair-> datas.add(repairInfoToVO((RepairEntity) repair)));
        
        page.setList(datas);
        
        return page;
    }
    
    @Override
    public RepairVo getRepairInfo(Integer repairId) {
        //RepairEntity repair = getById(repairId);
        RepairVo repairVo = repairInfoToVO(getById(repairId));
        List<Map<String, Object>> manifestList = manifestDao.getManifestVoByRepairId(repairId);
        List<ManifestVO> manifestVOList = manifestList.stream().map(map -> BeanUtil.mapToBeanIgnoreCase(map, ManifestVO.class, true)).collect(Collectors.toList());
        manifestVOList.forEach(m ->{
            m.setTypeTrans(TransUtils.getRepairTypeTrans(m.getTypeId()));
            m.setManifestTransLsit(transformMainfest(JSONObject.parseObject(m.getManifestList())));
        });
        repairVo.setManifestLists(manifestVOList);
        
        // 车辆信息
        CarEntity car = repairVo.getCar();
        // 匹配车型
        car.setCarTypeTrans(TransUtils.getCarTypeTrans(car.getCarType()));
        // 匹配车辆标签
        List<String> typeLists = carTypeRelationDao.selectDictListByCarId(car.getCarId());
        String typeTrans = typeLists.stream().map(TransUtils::getCarTypeTrans).collect(Collectors.joining(","));
        car.setCarDict(StringUtils.join(typeLists, ","));
        car.setCarDictTrans(typeTrans);
    
        return repairVo;
    }
    
    private List<Map<String, Object>> transformMainfest(Map<String, Object> manifestList) {
        List<Map<String, Object>> rtns = new ArrayList<>(manifestList.size());
        manifestList.forEach((k, v) ->{
            Map<String, Object> temp = new HashMap<>(2);
            temp.put("category", k);
            temp.put("trans", TransUtils.getRepairTypeTrans(k));
            temp.put("cost", v);
            rtns.add(temp);
        });
        
        return rtns;
    }
    
    @Override
    public void deleteRepairByIds(RepairDeleteReq req) {
        repairDao.deleteRepairByIds(req.getRepairLists());
    }
    
    @Override
    public List<CarTypeEntity> listRepaidDict(String pid) {
        return TransUtils.getRepairTypeDictByPid(pid);
    }
    
    @Override
    public R payRepair(Integer repairId) {
        RepairEntity repair = repairDao.selectRepairById(repairId);
        if (repair.getPaid().equalsIgnoreCase("1")){
            return R.error("该订单已经缴费");
        }
        if (repair.getRepaired().equalsIgnoreCase("0")){
            return R.error("该订单尚未完成，无法缴费");
        }
        repair.setPaid("1");
        repairDao.save(repair);
        return R.success("缴费成功");
    }
    
    /**
     * 补全repair信息，转为map
     * @author zyzhao
     * @date 2022/4/17 20:58
     * @param repair 要转化的信息
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    private RepairVo repairInfoToVO(RepairEntity repair) {
        RepairVo repairVo = new RepairVo();
        repairVo.setApplyId(repair.getApplyId());
        repairVo.setUser(tbUserDao.selectById(repair.getUserId()));
        repairVo.setCar(carDao.selectById(repair.getCarId()));
        repairVo.setShop(shopService.getById(repair.getShopId()));
        repairVo.setBeginTime(DateUtils.transferLongToDate(repair.getBeginTime()));
        repairVo.setEndTime(DateUtils.transferLongToDate(repair.getEndTime()));
        repairVo.setPrice(repair.getRepairPrice());
        repairVo.setRepaired(repair.getRepaired());
        return repairVo;
    }
    
}